import isHotkey from "is-hotkey";
export class KeyboardEvent {
  constructor(editor, container, view) {
    this.editor = editor;
    this.container = container;
    this.view = view;
    this.isComposing = false; // 是否处理中文输入过程中
  }
  beforeInputHandler_(e) {
    const inputType = e.inputType;
    // 没完全输入的时候不进入逻辑
    if (
      inputType === "insertCompositionText" ||
      inputType === "deleteCompositionText"
    ) {
      return;
    }
    e.preventDefault();
    let text;
    switch (inputType) {
      case "insertText":
        text = e.data;
        if (text) {
          this.editor.insertTextAtCursor(text);
        }
        break;
      case "insertParagraph":
        this.editor.insertTextAtCursor("\n");
        break;
      case "deleteContentBackward":
        this.editor.deleteTextAtCursor();
        break;
      case "insertFromPaste":
        // 粘贴
        const data = e.dataTransfer;
        text = data.getData("text/plain");
        if (text) {
          this.editor.insertTextAtCursor(text);
        }
        break;
    }
  }
  compositionStartHandler_(e) {
    this.isComposing = true;
  }

  compositionEndHandler_(e) {
    this.isComposing = false;
    const text = e.data;
    if (text) {
      this.editor.insertTextAtCursor(text);
    }
  }
  selectionchangeHandler_(selection) {
    if (selection && !this.isComposing) {
      this.editor.setSelection(selection.anchor, selection.focus);
    }
  }
  // 处理组合键或者的事件
  keydownHandler_(e) {
    if (isHotkey("mod+z", e)) {
      e.preventDefault();
      this.editor.undo();
    }
    if (isHotkey("mod+x", e)) {
      e.preventDefault();
      this.editor.redo();
    }
    if (isHotkey("mod+m", e)) {
      e.preventDefault();
      this.editor.changeRenderSourceAndPreview();
    }
  }

  addListeners() {
    this.container.addEventListener(
      "beforeinput",
      this.beforeInputHandler_.bind(this)
    );
    this.container.addEventListener("keydown", this.keydownHandler_.bind(this));
    this.container.addEventListener(
      "compositionstart",
      this.compositionStartHandler_.bind(this)
    );
    this.container.addEventListener(
      "compositionend",
      this.compositionEndHandler_.bind(this)
    );
    this.view.on("selection-change", this.selectionchangeHandler_.bind(this));
  }
}
export default KeyboardEvent;
